package com.konsung.ksdc.manager.user;

import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.konsung.ksdc.R;
import com.konsung.ksdc.common.network.RequestCallback;
import com.konsung.ksdc.common.network.RequestUtils;
import com.konsung.ksdc.common.network.ResponseBean;
import com.konsung.ksdc.common.utils.Constants;
import com.konsung.ksdc.common.utils.StringUtils;
import com.konsung.ksdc.config.NetConfig;
import com.konsung.ksdc.manager.appmain.BaseActivity;

import butterknife.Bind;
import butterknife.ButterKnife;
import okhttp3.Call;

/**
 * 手机验证页面
 * Created by Administrator on 2016/3/10 0010.
 */
public class BindPhoneActivity extends BaseActivity implements View.OnClickListener {

    public static final String USER_PHONE = "userPhone";
    @Bind(R.id.btn_checkcode_next)
    Button btnNext;
    @Bind(R.id.btn_getcode)
    Button btnGetCode;
    @Bind(R.id.et_userphone)
    EditText etUserPhone;
    @Bind(R.id.rl_back)
    RelativeLayout rlBack;
    @Bind(R.id.et_checkcode)
    EditText etCheckCode;
    @Bind(R.id.tv_phone_unavailable)
    TextView tvPhoneUnavailable;
    @Bind(R.id.tv_title)
    TextView tvTitle;

    public boolean isChange = false;
    private boolean tag = true;
    private int i = 60;

    Thread thread = null;
    private String randomCode;
    private int what; // 是从哪个页面进入到该页面的 (忘记密码，注册，修改绑定手机)
    private String phone;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_forget_passcheck);

        ButterKnife.bind(this);

        btnNext.setOnClickListener(this);
        btnGetCode.setOnClickListener(this);
        rlBack.setOnClickListener(this);
        tvPhoneUnavailable.setOnClickListener(this);

        initView();
    }

    @Override
    protected String activityDesc() {
        return getString(R.string.page_phone_check);
    }

    /**
     * 初始化手机验证页面
     */
    private void initView() {
        tvTitle.setText(getString(R.string.title_bind_phone));
        btnNext.setText(getString(R.string.btn_confirm_bind));
        tvPhoneUnavailable.setVisibility(View.GONE);
        etUserPhone.setHint(getString(R.string.tips_new_phone));

        etCheckCode.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int
                    count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
            }

            @Override
            public void afterTextChanged(Editable s) {
                if (s.length() == 4) {
                    String phone = etUserPhone.getText().toString().trim();
                    if (!TextUtils.isEmpty(phone)) {
                        btnNext.setEnabled(true);
                        btnNext.setBackgroundResource(R.drawable.btn_login_bg);
                    }
                } else {
                    btnNext.setEnabled(false);
                    btnNext.setBackgroundResource(R.drawable.bg_grey_round);
                }
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_checkcode_next:
                String inputCode = etCheckCode.getText().toString().trim();
                if (checkEmpty()) {
                    return;
                }

                if (inputCode.equals(randomCode)) {
                    String userPhone = etUserPhone.getText().toString().trim();
                    updatePhone(userPhone);
                } else {
                    Toast.makeText(this, R.string.tip_checked_error,
                            Toast.LENGTH_SHORT).show();
                    return;
                }

                break;
            case R.id.btn_getcode:
                if (checkPhoneEmpty()) {
                    break;
                }
                String phone = etUserPhone.getText().toString().trim();

                if (!RequestUtils.checkNetwork(this)) {
                    return;
                }
                if (!checkPhoneValidate()) {
                    return;
                }
                findPhone(phone);

                break;
            case R.id.rl_back:
                finish();
                break;
            case R.id.tv_phone_unavailable:
                Intent intent1 = new Intent(this,
                        PhoneUnavailableActivity.class);
                startActivity(intent1);
                break;
            default:
                break;
        }
    }

    /**
     * 修改绑定手机
     * @param phone 手机号码
     */
    private void updatePhone(String phone) {
        if (!RequestUtils.checkNetwork(this)) {
            return;
        }
        RequestUtils.updateTelephone(NetConfig.currentEmpid,
                phone, new RequestCallback() {
                    @Override
                    public void onError(Call call, Exception e) {
                        Toast.makeText(BindPhoneActivity.this,
                                R.string.tip_phone_change_failed,
                                Toast.LENGTH_SHORT).show();
                    }

                    @Override
                    public void onResponse(ResponseBean responseBean) {
                        Toast.makeText(BindPhoneActivity.this,
                                R.string.tip_phone_change_success,
                                Toast.LENGTH_SHORT).show();
                        finish();
                    }
                });
    }

    /**
     * 查询手机号码根据userName
     * @param phone 手机号码
     */
    private void findPhone(final String phone) {
        RequestUtils.findTelephone(phone, new RequestCallback() {
            @Override
            public void onError(Call call, Exception e) {
            }

            @Override
            public void onResponse(ResponseBean responseBean) {
                String resultCode = responseBean.getResultCode();
                if (resultCode.equals(Constants.REQUEST_OK)) {
                    Toast.makeText(BindPhoneActivity.this,
                            getString(R.string.phone_binded),
                            Toast.LENGTH_SHORT).show();
                } else {
                    // ### 界面 ###
                    btnGetCode.setText(R.string
                            .btn_get_checkcode);
                    btnGetCode.setClickable(true);
                    isChange = true;
                    changeBtnGetCode();

                    // ### 数据 ###
                    randomCode = StringUtils.getRandomCode();
                    RequestUtils.getCheckCode(phone, randomCode);
                }
            }
        });
    }

    /**
     * 检查输入的手机号码是否有效合法
     * @return true 有效  false 无效
     */
    private boolean checkPhoneValidate() {
        if (checkPhoneEmpty()) {
            return false; // 检查是否为空
        }
        if (!StringUtils.isPhoneNumberValid(etUserPhone.getText().toString()
                .trim())) {
            Toast.makeText(this, R.string.tip_phone_format_error, Toast
                    .LENGTH_SHORT).show();
            return false;
        }

        return true;
    }

    /**
     * 校验phone输入 empty
     * @return 是否为空 true为空
     */
    private boolean checkPhoneEmpty() {
        if (TextUtils.isEmpty(etUserPhone.getText().toString())) {
            Toast.makeText(this, R.string.tip_phone_not_empty, Toast
                    .LENGTH_SHORT).show();
            return true;
        }

        return false;
    }

    /**
     * 校验验证码输入 empty
     * @return 是否为空 true为空
     */
    private boolean checkCodeEmpty() {
        if (TextUtils.isEmpty(etCheckCode.getText().toString())) {
            Toast.makeText(this, R.string.tip_checkcode_not_empty, Toast
                    .LENGTH_SHORT).show();
            return true;
        }
        return false;
    }

    /**
     * 校验所有输入 empty
     * @return true代表存在空
     */
    private boolean checkEmpty() {
        if (checkPhoneEmpty()) {
            return true;
        }
        if (checkCodeEmpty()) {
            return true;
        }

        return false;
    }

    /**
     * 获取验证码后，读（60）秒的界面变化
     */
    private void changeBtnGetCode() {
        thread = new Thread() {
            @Override
            public void run() {
                if (tag) {
                    while (i > 0) {
                        i--;
                        if (BindPhoneActivity.this == null) {
                            break;
                        }
                        BindPhoneActivity.this.runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                btnGetCode.setText("" + i + "s");
                                btnGetCode.setClickable(false);
                                btnGetCode.setBackgroundResource(R.drawable
                                        .bg_grey_round);
                            }
                        });
                        try {
                            Thread.sleep((long) 1000);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    tag = false;
                }
                i = 60;
                tag = true;
                if (BindPhoneActivity.this != null) {
                    BindPhoneActivity.this.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            btnGetCode.setText(R.string.btn_get_checkcode);
                            btnGetCode.setBackgroundResource(R.drawable
                                    .btn_login_bg);
                            btnGetCode.setClickable(true);
                        }
                    });
                }
            }
        };
        thread.start();
    }
}
